﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Mvc;
using System.Web.Script.Serialization;
using System.Web.Security;
using NBlock.Core;
using NBlock.MVCExtensions;
using System.Configuration;
using StackExchange.Profiling;
using StackExchange.Profiling.MVCHelpers;
namespace Cost.Controllers
{
    public class HomeController : NBlock.Log.BaseController
    {
        private string ServerConnection = ConfigurationManager.AppSettings["ServerConnection"];
        private string Database = ConfigurationManager.AppSettings["LogDatabase"];
        NBlock.Log.MongoDbStorage db;

        #region 构造函数
        private readonly IUserService userService;
        private readonly IPrivilegeService privilegeService;

        public HomeController(IUserService userService, IPrivilegeService privilegeService)
        {
            this.userService = userService;
            this.privilegeService = privilegeService;
            db = new NBlock.Log.MongoDbStorage("", ServerConnection, Database);
        }
        #endregion

        #region 登陆相关Action
        //
        // GET: /Home/Login

        public ActionResult Login(string ReturnUrl)
        {
            ViewBag.RedirectUrl = string.IsNullOrEmpty(ReturnUrl) ?
                 Url.ActionLink<HomeController>(c => c.Index()) : ReturnUrl;
            return View();
        }

        //
        // Post: /Home/Login

        [HttpPost]
        public JsonResult Login(string userCode, string password)
        {
            var userId = userService.ValidUser(userCode, password);
            if (!string.IsNullOrEmpty(userId))
            {
                FormsAuthentication.SetAuthCookie(userId, false);
                db.Insert("用户登录", MiniProfiler.Current.Id.ToString());
                return Json(nbAjaxMessage.Successful);
            }
            else
            {
                return Json(new nbAjaxMessage
                {
                    IsSuccess = false,
                    Msg = "用户名或密码是否记错了，好好想想！",
                });
            }
        }

        //
        // GET: /Home/Logout

        public ActionResult Logout()
        {
            Session.Abandon();
            FormsAuthentication.SignOut();
            return Redirect(FormsAuthentication.LoginUrl);
        }
        #endregion

        #region 首页及左边菜单数据

        //
        // GET: /Home/

        public ActionResult Index()
        {
            ViewBag.UserName = nbUserContext.Current.CurrentUser.UserName;
            ViewBag.UserId = nbUserContext.Current.CurrentUser.UserId;

            return View();
        }

        //
        // GET: /Home/Menu

        public JavaScriptResult Menu()
        {
            var menus = privilegeService.GetMenuPrivileges() as List<IPrivilege>;
            List<nbJsonTreeNode> list = BuildSubTreeNode(menus);

            JavaScriptSerializer s = new JavaScriptSerializer();
            StringBuilder sb = new StringBuilder();
            s.Serialize(list, sb);
            sb.Insert(0, "var menudata=");
            return JavaScript(sb.ToString());
        }

        /// <summary>
        /// 组建树状结构的数据
        /// </summary>
        /// <param name="allmenus"></param>
        /// <param name="menus"></param>
        /// <returns></returns>
        private List<nbJsonTreeNode> BuildSubTreeNode(List<IPrivilege> menus, string parentId = "")
        {
            parentId = parentId ?? string.Empty;
            var list = new List<nbJsonTreeNode>();
            foreach (var p in menus.Where(m => m.ParentId == parentId))
            {
                if (nbUserContext.Current.HasRight(p.Id))
                {
                    var treenode = new nbJsonTreeNode();
                    treenode.id = p.Code;
                    treenode.text = p.Name;
                    treenode.value = GetHttpPath(p.Url);
                    treenode.isexpand = list.Count > 5 ? false : true;
                    treenode.showcheck = false;
                    treenode.complete = true;
                    treenode.ChildNodes = BuildSubTreeNode(menus, p.Id);
                    list.Add(treenode);
                }
            }
            return list;
        }

        /// <summary>
        /// 获取超链接的全路径
        /// </summary>
        /// <param name="path"></param>
        /// <returns></returns>
        private string GetHttpPath(string path)
        {
            if (!string.IsNullOrEmpty(path))
            {
                if (path.ToLower().StartsWith("http://") || path.ToLower().StartsWith("https://"))
                {
                    return path;
                }
                if (path.StartsWith("~/"))
                {
                    return Url.Content(path);

                }
                return path;
            }
            return "";
        }

        #endregion

        #region portal
        //
        // GET: /Home/Portal

        public ActionResult Portal()
        {
            return View();
        }
        #endregion
    }
}
